<template>
  <div class="role-management-container">
    <!-- Search and Add Role Area -->
    <div class="bg-white p-4 rounded-t-lg">
      <div class="flex items-center justify-between">
        <div class="flex gap-2">
          <!-- <el-input
            v-model="searchParams.name"
            :placeholder="t('role.roleName')"
            clearable
            :prefix-icon="Search"
          />
          <el-select
            v-model="searchParams.organizationType"
            :placeholder="t('role.organizationType')"
            clearable
            style="width: 200px"
          >
            <el-option :label="t('role.installer')" :value="1" />
            <el-option :label="t('role.distributor')" :value="2" />
          </el-select>
          <el-select
            v-model="searchParams.authorityType"
            :placeholder="t('role.authorityType')"
            clearable
            style="width: 200px"
          >
            <el-option :label="t('role.web')" value="0" />
            <el-option :label="t('role.app')" value="1" />
            <el-option :label="t('role.webApp')" value="0,1" />
          </el-select> 
          <el-button type="primary" @click="handleSearch">{{ t('common.search') }}</el-button>-->
        </div>
        <el-button v-if="hasPermission('sys:role:save') || isSuperAdmin" @click="handleAddRole">
          {{ t('authority.role.addRole') }}
        </el-button>
      </div>
    </div>

    <!-- Role List Table -->
    <div class="table-container bg-white p-4 rounded shadow-sm">
      <PageState :loading="loading" :error-message="errorMessage" :has-data="tableData.length > 0" @retry="retryFetch">
        <div class="table-wrapper">
          <el-table :data="tableData" border height="100%" class="adaptive-table design-table" table-layout="auto"
            :header-cell-style="headerCellStyle">
            <!-- 数据列 - 完全自适应宽度 -->
            <el-table-column prop="roleName" :label="t('authority.role.roleName')" min-width="120"
              class-name="data-column" />
            <el-table-column prop="organizationType" :label="t('authority.role.organizationType')" min-width="120"
              class-name="data-column">
              <template #default="scope">
                <span v-if="scope.row.organizationType === 0">Zendure</span>
                <span v-else-if="scope.row.organizationType === 1">{{ t('authority.role.installer') }}</span>
                <span v-else-if="scope.row.organizationType === 2">{{ t('authority.role.distributor') }}</span>
                <span v-else-if="scope.row.organizationType === 3">{{ t('authority.role.organizationalClient') }}</span>
                <span v-else>{{ scope.row.organizationType }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="authorityType" :label="t('authority.role.authorityType')" min-width="120"
              class-name="data-column">
              <template #default="scope">
                <el-tag v-if="scope.row.authorityType === '0'" type="primary">Web</el-tag>
                <el-tag v-else-if="scope.row.authorityType === '1'" type="success">App</el-tag>
                <el-tag v-else-if="scope.row.authorityType === '0,1' || scope.row.authorityType === '1,0'"
                  type="warning">Web+App</el-tag>
                <el-tag v-else-if="scope.row.authorityType === 0" type="primary">Web</el-tag>
                <el-tag v-else-if="scope.row.authorityType === 1" type="success">App</el-tag>
                <el-tag v-else type="info">{{ scope.row.authorityType || '-' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" :label="t('authority.role.status')" min-width="100" class-name="data-column">
              <template #default="scope">
                <status-indicator :status="scope.row.status" :active-text="t('authority.role.enable')"
                  :inactive-text="t('authority.role.disable')" />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" :label="t('authority.role.createTime')" min-width="150"
              class-name="data-column" />
            <el-table-column prop="modifyTime" :label="t('authority.role.modifyTime')" min-width="150"
              class-name="data-column" />
            <el-table-column prop="modifyUser" :label="t('authority.role.modifyUser')" min-width="120"
              class-name="data-column" />

            <!-- 操作列 - 固定宽度，始终在右侧 -->
            <el-table-column :label="t('authority.common.operation')" width="200" align="center" fixed="right"
              class-name="operation-column">
              <template #default="scope">
                <div class="operation-buttons">
                  <el-tooltip 
                    :content="scope.row.status === 1 && Number(scope.row.isGrey) === 1 ? 'This role is linked to an account and cannot be disabled' : ''"
                    :disabled="!(scope.row.status === 1 && Number(scope.row.isGrey) === 1)"
                    placement="top">
                    <el-button
                      v-if="hasAnyPermission(['sys:role:update', 'sys:role:update', 'sys:role:update']) || isSuperAdmin"
                      link type="primary"
                      :disabled="scope.row.status === 1 && Number(scope.row.isGrey) === 1"
                      @click="handleToggleStatus(scope.row)">
                      {{ scope.row.status === 1 ? t('authority.role.disable') : t('authority.role.enable') }}
                    </el-button>
                  </el-tooltip>
                  <el-button v-if="hasPermission('sys:role:update') || isSuperAdmin" link type="primary"
                    @click="handleModify(scope.row)">
                    {{ t('authority.common.modify') }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- Pagination -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50,100]"
            layout="total, prev, pager, next, sizes, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </PageState>
    </div>

    <!-- Role Form Drawer Component -->
    <role-form-drawer v-model:visible="drawerVisible" :form-data="formData" :dialog-type="dialogType"
      @submit-success="handleDialogSuccess" />

    <!-- Status Dialog Component -->
    <status-dialog v-model:visible="statusDialogVisible" :role-name="currentRoleName" :action="currentAction"
      @confirm="confirmToggleStatus" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineAsyncComponent } from "vue";
import { Search, OfficeBuilding } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getRoleList, addRole, updateRole, toggleRoleStatus, deleteRole } from "./data";
import { useI18n } from "@/composables/useI18n";
import { usePermission } from "@/composables/usePermission";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";
import { logger } from "@/utils/logger";

const StatusIndicator = defineAsyncComponent(() => import("@/components/status-indicator/StatusIndicator.vue"));

const RoleFormDrawer = defineAsyncComponent(() => import("./components/RoleFormDrawer.vue"));
const StatusDialog = defineAsyncComponent(() => import("./components/StatusDialog.vue"));

// 多语言
const { t } = useI18n();

// 权限与角色判断
const { hasPermission, hasAnyPermission, isSuperAdmin } = usePermission();

// 工具：规范化 authorityType，统一为 '0' | '1' | '0,1'
const normalizeAuthorityType = (input: any): string => {
  if (input == null) return "";
  let arr: string[] = [];
  if (Array.isArray(input)) {
    arr = input.map((x) => String(x));
  } else if (typeof input === "string") {
    arr = input
      .split(",")
      .map((s) => s.trim())
      .filter(Boolean);
  } else {
    arr = [String(input)];
  }
  // 文本到编码
  arr = arr.map((v) => (v === "Web" ? "0" : v === "App" ? "1" : v));
  // 去掉占位符
  arr = arr.filter((v) => v !== "-");
  // 去重并按 0,1 排序
  const set = Array.from(new Set(arr)).sort();
  if (set.length === 0) return "";
  if (set.length === 1) return set[0];
  return set.join(",");
};

// 搜索参数
const searchParams = reactive({
  roleName: "",
  organizationType: undefined as number | undefined,
  authorityType: ""
});

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const errorMessage = ref("");

// 表头样式：与设计稿一致的浅灰背景
const headerCellStyle = () => ({
  background: '#F5F6FA',
  color: '#111827',
  fontWeight: 600
});

// 抽屉控制
const drawerVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formData = ref({});

// 状态切换对话框
const statusDialogVisible = ref(false);
const currentRoleName = ref("");
const currentAction = ref("");
const currentRoleId = ref<string | null>(null);

// 初始化
onMounted(() => {
  loadTableData();
});

// 加载表格数据
const loadTableData = async () => {
  loading.value = true;
  try {
    // 构建查询参数，过滤掉空值
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value,
    };

    // 只有非空值才添加到参数中
    if (searchParams.roleName?.trim()) {
      params.roleName = searchParams.roleName.trim();
    }
    if (searchParams.organizationType !== undefined) {
      params.organizationType = searchParams.organizationType;
    }
    if (searchParams.authorityType !== undefined && searchParams.authorityType !== '') {
      params.authorityType = searchParams.authorityType;
    }

    const result = await getRoleList(params);

    // if (import.meta.env.DEV) logger.dev('API返回的原始数据:', result);

    // 处理数据，确保字段映射正确并规范化 authorityType
    tableData.value = result.list.map((item: any) => {
      // if (import.meta.env.DEV) logger.dev('处理前的数据项:', item);
      return {
        ...item,
        // 确保字段名映射正确
        roleName: item.roleName || item.name || '-',
        organizationType: item.organizationType || 0,
        authorityType: normalizeAuthorityType(item.authorityType) || '-',
        status: item.status !== undefined ? item.status : 0,
        // isGrey: 1 表示禁用按钮置灰（后端整数 1/0）
        isGrey: Number(item.isGrey ?? 0),
        createTime: item.createTime || item.createDate || '-',
        modifyTime: item.modifyTime || item.updateDate || '-',
        modifyUser: item.modifyUser || '-'
      };
    });

    // if (import.meta.env.DEV) logger.dev('处理后的表格数据:', tableData.value);

    total.value = result.totalCount;
  } catch (error) {
    logger.error('加载角色数据失败:', error);
    ElMessage.error(t('messages.loadDataFailed'));
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadTableData();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadTableData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadTableData();
};

// 添加角色
const handleAddRole = () => {
  dialogType.value = "add";
  // 清空表单数据，确保创建时表单是空的
  formData.value = {
    roleName: "",
    organizationType: 2, // 默认选择经销商
    authorityType: "1", // 默认选择App
    note: "",
    permissions: {}
  };
  drawerVisible.value = true;
};

// 修改角色
const handleModify = (row: any) => {
  dialogType.value = "edit";
  // 将表格行数据转换为表单所需字段
  formData.value = {
    ...row,
    id: String(row.id ?? ''),
    name: row.name || row.roleName || '',
    organizationType: Number(row.organizationType),
    status: Number(row.status),
    // 将表格里的 0/1 或 0,1 转为 Web/App 文本，便于抽屉直接用文本勾选
    authorityType: (() => {
      const s = String(row.authorityType ?? '').trim();
      if (!s) return '';
      return s.split(',')
        .map(x => x.trim())
        .map(x => (x === '0' ? 'Web' : x === '1' ? 'App' : x))
        .join(',');
    })(),
    note: row.note || ''
  };
  drawerVisible.value = true;
};

// 删除角色
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.roleName}" 吗？`,
      "确认删除",
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: "warning"
      }
    );

    const result = await deleteRole([String(row.id)]);
    if (result.success) {
      ElMessage.success(result.message);
      loadTableData();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      logger.error('删除角色失败:', error);
      ElMessage.error(t('messages.deleteFailed'));
    }
  }
};

// 切换状态
const handleToggleStatus = async (row: any) => {
  // 如果要禁用角色，先检查是否有账号使用该角色
  if (row.status === 1) {
    // 检查 isGrey 字段，如果为 1 表示角色正在被使用
    if (Number(row.isGrey) === 1) {
      ElMessage.warning('This role is linked to an account and cannot be disabled');
      return;
    }
    
    try {
      // 这里可以添加额外的API检查逻辑
      // const isRoleUsed = await checkRoleUsage(row.id);
      // if (isRoleUsed) {
      //   ElMessage.warning('该角色正在被使用，无法禁用');
      //   return;
      // }
    } catch (error) {
      logger.error('检查角色使用情况失败:', error);
    }
  }

  currentRoleName.value = row.roleName;
  currentRoleId.value = row.id;
  currentAction.value = row.status === 1 ? "disable" : "enable";
  statusDialogVisible.value = true;
};

// 确认切换状态
const confirmToggleStatus = async () => {
  try {
    if (!currentRoleId.value) {
      ElMessage.error('角色ID不存在');
      return;
    }

    const role = tableData.value.find((r: any) => r.id === currentRoleId.value);
    if (!role) {
      ElMessage.error('角色不存在');
      return;
    }

    const newStatus = role.status === 1 ? 0 : 1;
    const result = await toggleRoleStatus(role.id, newStatus);
    if (result.success) {
      ElMessage.success(result.message);
      statusDialogVisible.value = false;
      loadTableData();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    logger.error('切换状态失败:', error);
    ElMessage.error(t('messages.operationFailed'));
  }
};

// 抽屉提交成功回调
const handleDialogSuccess = async (formData: any) => {
  try {
    if (formData.isAdd) {
      // 添加：按API要求构造 payload（menuIdList: number[]）
      const payload = {
        name: formData.name,
        organizationType: Number(formData.organizationType),
        authorityType: String(formData.authorityType),
        note: formData.note || "",
        // 统一提交字符串数组，避免类型不一致
        menuIdList: Array.isArray(formData.menuIdList)
          ? formData.menuIdList.map((x: any) => String(x))
          : [],
        status: 1 // 创建时默认为启用状态
      };
      const result = await addRole(payload);
      if (result.success) {
        ElMessage.success(t('messages.roleAddSuccess'));
        // 新增成功后刷新菜单与权限，保证按钮展示即时生效
        const { useAppStore } = await import('@/store');
        await useAppStore().initApp();
      } else {
        ElMessage.error(result.message);
      }
    } else {
      // 更新：按API要求构造 payload（menuIdList: string[]）
      // 注意：显式带上当前状态，避免后端未传字段被重置
      const payload = {
        id: String(formData.id),
        name: formData.name,
        organizationType: Number(formData.organizationType),
        authorityType: String(formData.authorityType),
        note: formData.note || "",
        status: Number(formData.status),
        menuIdList: Array.isArray(formData.menuIdList)
          ? formData.menuIdList.map((x: any) => String(x))
          : []
      };
      const result = await updateRole(payload);
      if (result.success) {
        ElMessage.success(t('messages.roleUpdateSuccess'));
        // 更新成功后刷新菜单与权限
        const { useAppStore } = await import('@/store');
        await useAppStore().initApp();
      } else {
        ElMessage.error(result.message);
      }
    }

    drawerVisible.value = false;
    loadTableData();
  } catch (error) {
    logger.error('操作失败:', error);
    ElMessage.error(t('messages.operationFailed'));
  }
};

// 重试加载
const retryFetch = () => {
  errorMessage.value = "";
  loadTableData();
};

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  handleSearch();
}, 500, { leading: false, trailing: true });
</script>

<style lang="scss" scoped>
.role-management-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-container {
  flex-shrink: 0;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
}

/* 表格样式 - 与设计稿一致 */
.adaptive-table {

  // 设置表格布局为自动，实现完全自适应
  :deep(.el-table) {
    table-layout: auto;
    --el-table-border-color: #E5E7EB; // 全局分隔线颜色
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE and Edge */

    &::-webkit-scrollbar {
      display: none;
      /* Chrome, Safari, Opera */
    }
  }

  // 表头：统一浅灰背景，深色文字，加粗，圆角
  :deep(.el-table__header-wrapper),
  :deep(.el-table__header-wrapper th),
  :deep(.el-table__header-wrapper tr),
  :deep(.el-table__header-wrapper .cell),
  :deep(.el-table__header-wrapper thead),
  :deep(.el-table__header-wrapper thead tr),
  :deep(.el-table__header-wrapper thead tr th) {
    background-color: #F5F6FA !important;
    color: #111827 !important;
    font-weight: 600;
    border-bottom: 1px solid #E5E7EB !important;
    padding: 10px 16px;
  }

  // 表头左右圆角
  :deep(.el-table__header-wrapper thead tr th:first-child) {
    border-top-left-radius: 8px;
  }

  :deep(.el-table__header-wrapper thead tr th:last-child) {
    border-top-right-radius: 8px;
  }

  // 顶部细线颜色
  :deep(.el-table__inner-wrapper::before) {
    background-color: #E5E7EB !important;
    height: 1px;
  }

  // 表体：白底，文字颜色，底部分隔线，内边距
  :deep(.el-table__body tr),
  :deep(.el-table__body td) {
    background-color: #ffffff !important;
  }

  :deep(.el-table__body .el-table__cell) {
    color: #374151;
    padding: 12px 16px;
    border-bottom: 1px solid #E5E7EB !important;
  }

  // 行 hover 效果
  :deep(.el-table__body tr:hover > td) {
    background: #F9FAFB !important;
  }

  // 数据列完全自适应宽度
  :deep(.data-column) {
    .cell {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: keep-all;
    }
  }

  // 操作列固定样式，确保始终在右侧 - 实现"盖住"效果
  :deep(.operation-column) {
    position: sticky !important;
    right: 0 !important;
    z-index: 10 !important;
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1) !important;

    .cell {
      white-space: nowrap;
      overflow: hidden;
    }
  }

  // 操作按钮容器 - 链接风格
  .operation-buttons {
    display: flex;
    gap: 0;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;

    .el-button {
      flex-shrink: 0;
      min-width: auto;
      padding: 0 0; // 看起来像纯文本链接
      font-size: 13px;
      color: #0F766E; // 链接主色
    }

    .el-button:hover {
      color: #115E59;
      text-decoration: underline;
      background: transparent;
    }

    // 禁用按钮样式
    .el-button:disabled {
      color: #C0C4CC !important;
      cursor: not-allowed !important;
      
      &:hover {
        color: #C0C4CC !important;
        text-decoration: none !important;
        background: transparent !important;
      }
    }
  }



}

// 响应式设计
@media (max-width: 768px) {
  .adaptive-table {
    :deep(.el-table__body-wrapper) {
      overflow-x: auto;
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;
      /* IE and Edge */

      &::-webkit-scrollbar {
        display: none;
        /* Chrome, Safari, Opera */
      }
    }

    .operation-buttons {
      flex-direction: column;
      gap: 4px;

      .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>
